package cn.com.gridinfo.sooc.core.course.classes.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.jeremy.arad.utils.Log;
import com.jeremy.arad.utils.StringUtils;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;

import org.apache.http.message.BasicNameValuePair;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.base.BaseSoocActivity;
import cn.com.gridinfo.sooc.core.course.classes.adapter.CourseListAdapter;
import cn.com.gridinfo.sooc.core.course.classes.dao.CourseDao;
import cn.com.gridinfo.sooc.core.course.common.CodeConst;
import cn.com.gridinfo.sooc.utils.IntentUtil;
import cn.com.gridinfo.sooc.utils.MessageUtils;
import cn.com.gridinfo.sooc.utils.widget.ClearEditText;

/**
 * 课程搜索界面
 *
 * @author jie.li
 */
public class CourseSearchActivity extends BaseSoocActivity {


    @InjectView(R.id.tipBlank)
    TextView blankTip;//空白页提示
    @InjectView(R.id.course_main_list)
    UltimateRecyclerView courseMainRecyclerView;//搜索列表
    @InjectView(R.id.course_search)
    ClearEditText courseSearch;//搜索内容控件
    CourseListAdapter courseListAdapter;//课程列表适配器
    CourseDao dao;//课程分类 dao
    LinearLayoutManager linearLayoutManager;//列表管理器
    int pageNo = 1;
    int pageSize = 10;
    int maxLastPositon;//数据最后位置
    String searchTxt;// 搜索内容

    int clicki = 1;//点击搜索次数

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.course_search);
        ButterKnife.inject(this);
        //初始化listView
        linearLayoutManager = new LinearLayoutManager(this);
        courseMainRecyclerView.setLayoutManager(linearLayoutManager);
        dao = new CourseDao(this);
        //设置空白页提示
        blankTip.setText("没有找到相关课程，换个词试试？");

        courseSearch.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        //键盘搜索监听
        courseSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH)
                {
                    //执行搜索
                    onSearchCourse();
                }
                return false;
            }
        });
    }

    //返回
    @OnClick(R.id.go_back)
    void onGoBack() {
        finish();
    }

    //搜索
    @OnClick(R.id.go_search)
    void onSearchCourse() {
//        courseMainRecyclerView.hideEmptyView();
        searchTxt = courseSearch.getText().toString().trim();
        if(StringUtils.isNull(searchTxt)){
            //搜索内容为空时，不继续进行
            return;
        }
        //第一次点击
        if(clicki == 1) {

            dao.getCourseListByPage("", searchTxt, pageNo, CodeConst.COURSE_LIST_FIRST);
        }else {
            //下拉刷新 搜索课程数据
            pageNo = 1;//首页
            dao.getCourseListByPage("", searchTxt, pageNo, CodeConst.COURSE_LIST_PUSHDOWN);
            courseMainRecyclerView.setRefreshing(false);
            linearLayoutManager.scrollToPosition(0);
        }
        clicki++;
        //隐藏软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(courseSearch.getWindowToken(), 0);
    }

    /**
     * 请求成功
     */
    @Override
    public void onRequestSuccess(int requestCode) {
        try {
            if (dao.status.equals("0")) {
                switch (requestCode) {
                    //课程首次请求
                    case CodeConst.COURSE_LIST_FIRST:
                        initCourseList();

                        break;

                    //课程刷新操作
                    case CodeConst.COURSE_LIST_PUSHDOWN:
                        courseMainRecyclerView.setRefreshing(false);

                        if (dao.getCourseList() != null && !dao.getCourseList().isEmpty()) {
                            courseMainRecyclerView.hideEmptyView();
                        } else {
                            //无数据处理
                            courseMainRecyclerView.showEmptyView();
                        }
                        //刷新数据
                        courseListAdapter.refresh(dao.getCourseList());


                        if (dao.getCourseList().size() > (pageSize - 1)) {
                            //数据大于每页显示的条数,则加载更多数据
                            courseListAdapter.loadMoreDataView();
                        }
                        else {
                            //数据小于当前页的话则不显示加载更多,显示没有更多了
                            courseListAdapter.loadNoDataView();
                            linearLayoutManager.scrollToPositionWithOffset(maxLastPositon, -1);
                        }
                        break;

                    //课程翻页操作
                    case CodeConst.COURSE_LIST_PULLUP:
                        if (dao.getCourseList() != null && !dao.getCourseList().isEmpty()) {
                            //加载更多
                            courseListAdapter.loadmore(dao.getCourseList());


                        } else {
                            //数据加载完成,没有更多数据,显示没有更多了
                            courseListAdapter.loadNoDataView();
                            //无数据则不显示下一页
                            linearLayoutManager.scrollToPositionWithOffset(maxLastPositon, -1);
                        }
                        break;

                }
            } else {
                MessageUtils.showImageShortToast(this, dao.statusCode);
            }

        } catch (Exception e) {

            Log.e("请求数据异常:" + e.getMessage());
            MessageUtils.showImageShortToast(this, e.getMessage());
        }
    }


    /**
     * 初始化 list 数据 分页
     */
    public int getScreenHeight() {
        return findViewById(android.R.id.content).getHeight();
    }

    private void initCourseList() {


        courseListAdapter = new CourseListAdapter(dao.getCourseList(), this);
        courseMainRecyclerView.setAdapter(courseListAdapter);
        courseMainRecyclerView.enableLoadmore();
        courseMainRecyclerView.setDefaultOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //下拉刷新 搜索课程数据
                pageNo = 1;//首页
                dao.getCourseListByPage("", searchTxt, pageNo, CodeConst.COURSE_LIST_PUSHDOWN);
                linearLayoutManager.scrollToPosition(0);
            }
//                }, 1000);
//            }
        });
        courseMainRecyclerView.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() {
            @Override
            public void loadMore(final int itemsCount, final int maxLastVisiblePosition) {
                if (itemsCount > (pageSize - 1)) {
                    maxLastPositon = maxLastVisiblePosition;
                    dao.getCourseListByPage("", searchTxt, ++pageNo, CodeConst.COURSE_LIST_PULLUP);
                } else {
                    //加载数据完成,没有更多数据,显示没有更多了
                    courseListAdapter.loadNoDataView();
                    linearLayoutManager.scrollToPositionWithOffset(maxLastVisiblePosition, -1);
                }
            }
//            }
        });
        courseListAdapter.setmOnItemClickLitener(new CourseListAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, int position) {
                Log.d("点击第" + position + "个");
                String kcid = courseListAdapter.courseList.get(position).getKcid();
                String kcfm = courseListAdapter.courseList.get(position).getKcfm();
                Log.d("课程ID:" + kcid);
                IntentUtil.intentSlidIn(CourseSearchActivity.this, CourseDetailActivity.class, 00, new BasicNameValuePair("kcid", kcid), new BasicNameValuePair("kcfm", kcfm));
            }
        });
    }


}
